<?php
namespace app\common\model\orderdelivery;

use think\Model;
use think\Db;
use think\facade\Session;
use app\common\model\user\User;
use app\common\model\company\Company;
use app\common\model\quotation\QuotationList;
use app\common\model\orderdata\Goods;
use app\common\model\coll\Collection;
use app\common\model\buss\Buss;
use app\common\model\cost\Costtype;
use app\common\model\power\Rolepower;

class DeliveryList extends Model
{
     // 设置当前模型对应的完整数据表名称
        protected $table = 'deliverylist';
        protected $pk = 'DeliveryListId';
        
        const STATEINT = 0;//创建状态
        const STATEWAIT = 0;//等待配货
        const STATEWAITOK = 1;//待出库
        const STATETRANSPORT = 2;//待回执
        const STATEOK = 3;//订单完成
        const STATEDELETE = 404;//被删除的订单
        const STATEARRAY = [['待提单','已提单'],['待配货','已配货'],['待出库','已出库'],['待回执','已回执']];

    public function wareinfo(){
         return $this->hasOne('app\common\model\user\User','UserId','WarehouseId');
    }
    public function dispinfo(){
         return $this->hasOne('app\common\model\orderdelivery\Disposalsite','DisposalSiteId','DisposalSiteId');
    }
    public function listinfo(){
        return $this->hasMany('app\common\model\orderdelivery\Delivery','DeliveryListId','DeliveryListId');
    }

	public function delivery()
	{
		return $this->hasMany(Delivery::class, 'DeliveryListId', 'DeliveryListId');
    }

    /**
     * 状态分类
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1=>'全部订单',0=>'待配货',1=>'已配货',2=>'待回执',3=>'已回执'];
        if($value!==''){
            return $status[$value];
        }
        return $status;
    }

    /**
     * 获取订单列表
     * @param  [type] $data    [主数据]
     * @param  string $type    [查询类型/hawa/buss]
     * @param  [type] $is_page [是否分页显示]
     * @return [type]          [description]
     */
    public static function usergetlist($data,$type = 'hawa',$is_page = true){

        $rdata = DeliveryList::where('State','<>',DeliveryList::STATEDELETE);
        $userinfo = User::getinfo();
    
        if($type=='acco'||$type=='mana'){
            $rdata = $rdata->with(['dispinfo','listinfo','wareinfo']);
            $visible = ['DeliveryListId','State','UpTime','SettlementTime','WarehouseTime','SettlementTime','TotalCost','dispinfo.DisposalSiteName'];
        }else if($type=='ware'){
            $rdata = $rdata->with(['dispinfo','listinfo','wareinfo']);
            $visible = ['DeliveryListId','State','UpTime','WarehouseTime','dispinfo.DisposalSiteName'];
        }else{
            return moerr('缺少参数');
        }
        $option = come_model_option($data,$rdata,$is_page);
        $rdata = $option['rdata'];
        $data = $option['data'];
  
        $rdata = $rdata->select();
        $rdata =  $rdata->visible($visible);

        $ndata['list'] = $rdata->toArray();
        $goodid = get_array_id($ndata,'GoodId','list','listinfo');
        $ndata['goodinfo'] = Goods::getlist($goodid);
        $ndata['statetext'] = DeliveryList::getStatusText();
        if($is_page){
            $ndata['pageinfo'] = ['pageindex'=>$data['pageindex'],'pagemax'=>$data['count']];
        }
        return $ndata;
    }

     /**
     * 判断列表中的产品状态是否可操作
     * @param  [type] $list [id数组]
     * @return [type]       [返回错误代码]
     */
    public static function liststate($id,$hidden=[],$hidloag=true){
        $data = DeliveryList::where('State','<>',DeliveryList::STATEDELETE)->where('DeliveryListId',$id)->find();
	    if(empty($data)){
            return moerr('没有找到您需要的订单');
        }else{
	    	$data->delivery;
//	    	dump($data);die;
            if($hidloag){
                $hidden= array_merge(['OperationLog'],$hidden);
                $data = $data->hidden($hidden)->toArray();
            }elseif(empty($hidden)){
                $data = $data->toArray();
            }else{
                $data = $data->hidden($hidden)->toArray();    
            }
            return sok($data);
           
        }
    }
    /**
     * 获取订单信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getinfo($id,$type='ware'){
        if($type=='ware'){
            $data = self::liststate($id,['ReceiptImg','QuotationCost','FloatingCost','ReceiptNote','TotalCost','PostageCost','OtherCost','CostNote','SettlementImg','SettlementNote','SettlementTime']);
        }elseif($type=='mana'){
            $data = self::liststate($id,[],false);
        }else{
            $data = self::liststate($id);
        }

        if (!$data['code']) { return $data; }
        $rdata = $data['msg'];
        $rdata['GoodsList'] = Delivery::getlist($rdata,$type);
        if($type=='acco'){
            $rdata['acco'] = User::getpublicinfo($rdata['UpUserId']);
            $rdata['ware'] =(empty($rdata['WarehouseId']) ?[]:User::getpublicinfo( $rdata['WarehouseId'] ));
            $rdata['disp'] = Disposalsite::user_getinfo($rdata['DisposalSiteId']);
            $rdata['cost'] = Costtype::getcostlist($id,'orderdelivery');
        }else if($type=='ware'){
            $rdata['acco'] = User::getpublicinfo($rdata['UpUserId']);
            $rdata['ware'] =(empty($rdata['WarehouseId']) ?[]:User::getpublicinfo( $rdata['WarehouseId'] ));
            $rdata['disp'] = Disposalsite::user_getinfo($rdata['DisposalSiteId']);
        }else if($type=='mana'){
            $rdata['acco'] = User::getpublicinfo($rdata['UpUserId']);
            $rdata['ware'] =(empty($rdata['WarehouseId']) ?[]:User::getpublicinfo( $rdata['WarehouseId'] ));
            $rdata['disp'] = Disposalsite::user_getinfo($rdata['DisposalSiteId']);
            if(Rolepower::ispower(203008)){
                $rdata['cost'] = Costtype::getcostlist($id,'orderdelivery');
            }
        }else{
            return moerr('参数错误');
        }
        $rdata['StateList'] = DeliveryList::STATEARRAY;
        return ['code'=>true,'msg'=>$rdata]; 

    }

    /**
     * 新增方法
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function screate($idata){
        $userinfo = User::getinfo();
        //判断是否连续触发
        $sb = DeliveryList::where('UpUserId',$userinfo->UserId)->where('UpTime','>',date('Y-m-d H:i',time()-60))->find();
        if(!empty($sb)){
            return serr('在一分钟内您已下单，请于一分钟后尝试提交。');
        }
        if(empty($idata['DisposalSiteId'])){
            return moerr('请选择处置单位');
        }
        //基础信息
        $data['State'] = DeliveryList::STATEINT;
        $data['DisposalSiteId'] = $idata['DisposalSiteId'];
       
        //提单人信息
        $data['UpUserId'] = $userinfo->UserId;
        $data['UpNote'] = $idata['UpNote'];
        $data['UpTime'] = date('Y-m-d H:i',time());
        //保存主表
        $hawalist = DeliveryList::create($data);
       return sok($hawalist);
    }
    
    /**
     * 判断订单数组状态是否完全一致
     * @param  [type] $data  [description]
     * @param  [type] $state [description]
     * @return [type]        [description]
     */
    public static function test_state($data,$state){
        $sb = DeliveryList::where('DeliveryListId','in',$data)->where('State',$state)->count();
        if($sb==count($data)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 订单分配
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function dist($data){
        $userinfo = User::getinfo();
        if(!empty($data['ids'])){
            $sb =  DeliveryList::where('DeliveryListId','in',$data['ids']);
        }else if(!empty($data['id'])){
            $sb =  DeliveryList::where('DeliveryListId',$data['id']);
        }else{
            return moerr('分配参数错误');
        }
       
        $count = $sb->update(['DistributionTime' => date('Y-m-d H:i',time()),
                     'DistributionUserId'=>$userinfo->UserId,
                     'BussinessId'=>$data['bussid'],
                     'State'=>1]);
        if(empty($count)){
            return moerr('没有找到需要分配的订单');
        }
        return sok('成功分配'.$count.'个订单。');
    }

    /**
     * 修改收集员
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function changedist($data){
        $userinfo = User::getinfo();
        if(!empty($data['id'])&&!empty($data['bussid'])){
            $sb =  DeliveryList::where('DeliveryListId',$data['id'])->find();
        }else{
            return moerr('分配参数错误');
        }
        if($sb->State >= 3){
            return moerr('订单已在运输中无法修改收集员');
        }
        $sb->save(['DistributionTime' => date('Y-m-d H:i',time()),
                     'DistributionUserId'=>$userinfo->UserId,
                     'BussinessId'=>$data['bussid'],
                     'State'=>1]);
        return sok('修改成功');
    }


    /**
     * 修改收集员
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function changestate($iddata){
        $userinfo = User::getinfo();
        if(!empty($data['id'])&&!empty($data['bussid'])){
            $sb =  DeliveryList::where('DeliveryListId',$data['id'])->find();
        }else{
            return moerr('分配参数错误');
        }
        if($sb->State >= 3){
            return moerr('订单已在运输中无法修改收集员');
        }
        $sb->save(['DistributionTime' => date('Y-m-d H:i',time()),
                     'DistributionUserId'=>$userinfo->UserId,
                     'BussinessId'=>$data['bussid'],
                     'State'=>1]);
        return sok('修改成功');
    }


    
   /**
    * 用户修改信息
    * @param  [type]  $data   [description]
    * @param  boolean $wtnote [是否记录]
    * @return [type]          [description]
    */
    public static function user_reinfo($data,$wtnote=true){
        if(empty($data['id'])){
            return moerr('缺少重要参数');
        }
        $info = DeliveryList::get($data['id']);
        $userinfo = User::getinfo();
        $reinfo = empty($info->OperationLog)?'':$info->OperationLog."\n";
        $reinfo = $reinfo .'【' .$userinfo->Name.'|'.$userinfo->UserId.'】在'.date('Y-m-d H:i',time()).'进行了信息调整：';
        $nreinfo = '';
        foreach ($data as $key => $value) {
            $sb = $info->getfiledname($key);
            if(empty($sb)){
                continue;
            }
            //取原数据
            $ovalue = $info->$key;
            if($key=='State'&&$value!==$ovalue){
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value = $info->getStatusText((int)$value);
                $ovalue = $info->getStatusText((int)$ovalue);
                $nreinfo =  $nreinfo . '字段【'.$info->getfiledname($key).'】由【'.  $ovalue .'】修改为【' .$value.'】;'."\n";
            }else if($key=='DisposalSiteId'&&$value!==$ovalue){
                $info->$key = $value;
                $namedata = Disposalsite::getsitelistname([$value,$ovalue]);
                $value = $namedata[$value].'('.$value.')';
                $ovalue = $namedata[$ovalue].'('.$ovalue.')';
                $nreinfo =  $nreinfo . '字段【'.$info->getfiledname($key).'】由【'.  $ovalue .'】修改为【' .$value.'】;'."\n";
            }else if(!empty($value)&&$ovalue !== $value){
                $nreinfo =  $nreinfo . '字段【'.$info->getfiledname($key).'】由【'.  $ovalue .'】修改为【' .$value.'】;'."\n";
                $info->$key = $value;
            }
        }
        if(!empty($nreinfo)){
            if($wtnote){
                $reinfo = $reinfo ."\n" . $nreinfo;
                $info->OperationLog = $reinfo;
            }
            $info->save();
        }else{
            return moerr('没有找到需要调整的数据');
        }
    }

    public static function getfiledname($str){
        $filename = ['UpNote'=>'出库需求','UpImg'=>'下单附带图片','DisposalSiteId'=>'处置场',
                 'QuotationCost'=>'货物费用','FloatingCost'=>'浮差金额','ReceiptNote'=>'回执备注','ReceiptImg'=>'回执图片',
                 'TotalCost'=>'订单总费用',
                 'PostageCost'=>'运输费用','OtherCost'=>'其他费用','CostNote'=>'开支备注',
                 'SettlementImg'=>'结算凭证','SettlementTime'=>'结算时间','SettlementNote'=>'结算备注','State'=>'订单状态',
                 'WarehouseImg'=>'出库备注图片','WarehouseNote'=>'出库备注','WarehouseTime'=>'出库时间','WarehouseId'=>'库管ID'];
        if(empty($filename[$str])){
            return false;
        }
        return $filename[$str];
    }

    public static function getgoodinfo($bussid,$state){
        $idarr = DeliveryList::where('State',$state)->where('BussinessId',$bussid);
        $idarr = $idarr->column('DeliveryListId');
        $data = Delivery::where('DeliveryListId','in',$idarr)->group('GoodId')->with('good_info')->field('GoodId,sum(Weight) as Weight')->select();
        return $data;
    }
    /**
     * 货物入库登记
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function receipt($data){
        //检测勾选的订单状态
        if(!DeliveryList::test_state($data['DeliveryListIds'],DeliveryList::STATETRANSPORT)){
            return sok('勾选的订单状态无法直接入库');
        }
        //标记入库订单id
        DeliveryList::where('DeliveryListId','in',$data['DeliveryListIds'])->update(['ReceiptListId'=>$data['id'],'State'=>DeliveryList::STATEOK]);
        return sok();
    }

      /**
     * 获取统计数据
     * @return [type] [description]
     */
    public static function getsummary($date='',$enddate=''){
        if (empty($date)) {
            $date = date('Y-m-d',time());
        }else{
            $date = date('Y-m-d',strtotime($date));
        }
        if(empty($enddate)){
            $sb = DeliveryList::where('WarehouseTime','>',$date)->where('WarehouseTime','<=',$date.' 24:00')->field('TotalCost,DeliveryListId')->select();
            $rdata['timestr'] = mb_substr($date,8,2).'号';
        }else{
            $enddate = date('Y-m-d',strtotime($enddate));
            $sb = DeliveryList::where('WarehouseTime','>',$date)->where('WarehouseTime','<=',$enddate.' 24:00')->field('TotalCost,DeliveryListId')->select();
            if(mb_substr($date,5,2)!==mb_substr($enddate,5,2)){
                $rdata['timestr'] = mb_substr($date,5,5).'~'.mb_substr($enddate,6,5);
            }else{
                $rdata['timestr'] = mb_substr($date,8,2).'~'.mb_substr($enddate,8,2);
            }
        }
        if(empty($sb)){
            return [];
        }
        
        if(empty($enddate)){
            $rdata['wait'] = DeliveryList::where('WarehouseTime','>',$date)->where('WarehouseTime','<=',$date.' 24:00')->whereNull('SettlementTime')->count();
        }else{
            $rdata['wait'] = DeliveryList::where('WarehouseTime','>',$date)->where('WarehouseTime','<=',$enddate.' 24:00')->whereNull('SettlementTime')->count();
        }

        $Deliverylists = get_array_id($sb,'DeliveryListId');
        $rdata['goodlist'] = Delivery::where('DeliveryListId','in',$Deliverylists)->group('GoodId')->with('goodInfo')->field('GoodId,sum(Weight) as Weight,sum(ReceiptWeight) as ReceiptWeight')->select();
        $rdata['Weight'] = 0;
        foreach ($rdata['goodlist'] as $key => $value) {
             $rdata['Weight'] = $value['Weight'] + $rdata['Weight'];
        }
        
        
        if($rdata['Weight']>1000){
            $rdata['Weight'] = $rdata['Weight'] / 1000;
            $rdata['WeightUnit'] = '吨';
        }else{
            $rdata['WeightUnit'] = '公斤';
        }
        $rdata['Price'] = 0;
        foreach ($sb as $key => $value) {
             $rdata['Price'] = $value['TotalCost'] +  $rdata['Price'];
        }
        if($rdata['Price']>1000){
            $rdata['Price'] = $rdata['Price'] / 10000;
            $rdata['PriceUnit'] = '万元';
        }else{
            $rdata['PriceUnit'] = '元';
        }
        return $rdata; 
    }

}
